package com.ht.medicaltreatment.activity

import android.content.Context
import android.content.Intent
import android.os.Build
import android.view.View
import androidx.activity.viewModels
import androidx.lifecycle.Lifecycle
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.TimeUtils
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.listener.OnItemClickListener
import com.githang.statusbar.StatusBarCompat
import com.gym.baselib.base.BaseActivity
import com.gym.baselib.utils.runOnMain
import com.gym.baselib.utils.runOnThread
import com.ht.medicaltreatment.R
import com.ht.medicaltreatment.adapter.StockAdapter
import com.ht.medicaltreatment.bean.AssetVO
import com.ht.medicaltreatment.bean.LocationSubmitJson
import com.ht.medicaltreatment.bean.OrderSubmitJson
import com.ht.medicaltreatment.utils.SoundUtils
import com.ht.medicaltreatment.view.RemarkDialog
import com.ht.medicaltreatment.viewmodel.StockViewModel
import com.rscja.deviceapi.RFIDWithUHFUART
import com.xgst.lib.utils.showToast
import kotlinx.android.synthetic.main.activity_stock_layout.btnRemark
import kotlinx.android.synthetic.main.activity_stock_layout.btnSubmit
import kotlinx.android.synthetic.main.activity_stock_layout.imgCircleBg
import kotlinx.android.synthetic.main.activity_stock_layout.progress
import kotlinx.android.synthetic.main.activity_stock_layout.recyclerView
import kotlinx.android.synthetic.main.activity_stock_layout.tvCount
import kotlinx.android.synthetic.main.activity_stock_layout.tvErrorCount
import kotlinx.android.synthetic.main.activity_stock_layout.tvLoseCount
import kotlinx.android.synthetic.main.activity_stock_layout.tvName
import kotlinx.android.synthetic.main.activity_stock_layout.tvRealCount
import kotlinx.android.synthetic.main.activity_stock_layout.tvText1
import kotlinx.android.synthetic.main.activity_stock_layout.tvText2
import kotlinx.android.synthetic.main.activity_stock_layout.tvTime

/**
 * 盘点
 */
class StockActivity : BaseActivity(), OnItemClickListener {

    companion object{
        const val FROM_LOCATION = "1"
        const val FROM_ORDER = "2"
        fun getIntent(context: Context,id:Int,from:String):Intent{
            val intent = Intent(context,StockActivity::class.java)
            intent.putExtra("id",id)
            intent.putExtra("from",from)
            return intent
        }
    }

    private var isStart = false
    private var mReader:RFIDWithUHFUART? = null
    private val model by viewModels<StockViewModel>()
    private var isSubmit = false
    private var assetNum = 0
    private var id = -1
    private var remark = ""
    private var from:String? = null
    //接口返回的原始数据
    private var list:MutableList<AssetVO> = arrayListOf()
    //错放数量
    private val errorList = mutableSetOf<String>()
    //盘点全部的数量
    private val scanAllList = mutableSetOf<String>()
    //盘点正确的数量，就是应该有的uid
    private val scanRightList = mutableSetOf<String>()
    //缺失数量
    private val loseList = mutableSetOf<String>()
    //储存扫描的UID，优化重复扫描一直有提示音
    private val filterList = mutableSetOf<String>()

    private val mAdapter = StockAdapter()
    //uid位置信息
    private val mUidMap = mutableMapOf<String, AssetVO>()
    private lateinit var remarkDialog:RemarkDialog

    override fun getLayoutId() = R.layout.activity_stock_layout

    override fun init() {
        id = intent.getIntExtra("id",-1)
        from = intent.getStringExtra("from")
        StatusBarCompat.setStatusBarColor(this,getColor(R.color.blueDeep))
        remarkDialog = RemarkDialog(this)
        val linearLayoutManager = object : LinearLayoutManager(this){
            override fun canScrollVertically(): Boolean {
                return false
            }
        }
        mAdapter.setOnItemClickListener(this)
        recyclerView.layoutManager = linearLayoutManager
        recyclerView.adapter = mAdapter
        recyclerView.isNestedScrollingEnabled = false
        if("C72" == Build.MODEL){
            initUFC()
        }
        initData(id, from)
        initClick()
    }

    /**
     * 初始化超高频UFC
     */
    private fun initUFC() {
        try {
            mReader = RFIDWithUHFUART.getInstance()
            if(mReader != null){
                runOnThread {
                    val result = mReader?.init()
                    LogUtils.i("初始化UFC：$result")
                    mReader
                }
            }
        }catch (e:Exception){
            LogUtils.i("initUFC初始化失败: ${e.message}")
            return
        }
    }

    private fun initClick() {
        if(isSubmit){
            return
        }
        //确认报告
        btnSubmit.setOnClickListener {
            if(Build.MODEL == "C72" && isStart){
                openOrCloseUHF()
            }
            isSubmit = true
            tvTime.text = TimeUtils.getNowString(TimeUtils.getSafeDateFormat("yyyy-MM-dd HH:mm:ss"))
            val loseCount = assetNum - scanRightList.size
            tvLoseCount.text = "$loseCount"
            tvErrorCount.text = "${errorList.size}"
            tvRealCount.text = "${scanAllList.size}"
            var count = list.size
            val tempList = mutableListOf<AssetVO>()
            if(errorList.size > 0){
                errorList.forEachIndexed { index, s ->
                    LogUtils.i("提交报告  错放 ",errorList.size,index)
                    tempList.add(AssetVO(0,s,s,2,count+index))
                    //mAdapter.addData(AssetVO(0,s,s,2,count+index))
                }
            }
            mAdapter.addData(tempList)
            LogUtils.i("提交报告 adapter ",tempList.size,mAdapter.data.size)
            if(from == FROM_LOCATION){
                submitByLocation()
            }else{
                submitByOrder()
            }
        }

        //添加备注
        btnRemark.setOnClickListener {
            remarkDialog.showDialog(isSubmit){
                remark = it
                btnRemark.text = "查看备注"
            }
        }

        //开始盘点
        imgCircleBg.setOnClickListener {
            if(Build.MODEL == "C72"){
                //超高频
                openOrCloseUHF()
            }
        }
    }

    /**
     * 开启超高频
     */
    private fun openOrCloseUHF() {
        filterList.clear()
        if(mReader == null){
            showToast("UHF-开启失败")
            return
        }
        if(isSubmit){
            showToast("您已确认报告，无法再次盘点")
            return
        }
        if(isStart){
            //去关闭
            if(mReader?.stopInventory() == true){
                isStart = false
                tvText1.text = "开始"
                tvText1.setTextColor(getColor(R.color.blue))
                tvText2.setTextColor(getColor(R.color.blue))
            }else{
                showToast("停止失败")
            }
        }else{
            //去打开 - 开始
            errorList.clear()
            if(mReader?.startInventoryTag() == true){
                clearData()
                tvText1.text = "停止"
                tvText1.setTextColor(getColor(R.color.red))
                tvText2.setTextColor(getColor(R.color.red))
                isStart = true
                runOnThread {
                    loopReadUHF()
                }
            }else{
                showToast("开启失败")
                mReader?.stopInventory()
            }
        }
    }

    //复位数据
    private fun clearData() {
        progress.progress = 0
        val _list = arrayListOf<AssetVO>()
        list.forEach {
            _list += AssetVO(it.assetId,it.assetName,it.uid,0,it.index)
        }
        mAdapter.setNewInstance(_list)

        loseList.clear()
        errorList.clear()
        scanAllList.clear()
        scanRightList.clear()

        tvTime.text = ""
        tvLoseCount.text = "0"
        tvErrorCount.text = "0"
        tvRealCount.text = "0"
        btnRemark.text = "添加备注"
        remarkDialog.setContent("")
        //tvCount.text = "0"
    }

    private fun initData(id: Int, from: String?) {
        mUidMap.clear()
        if (id != -1 && from == null) {
            showProgress()
            model.requestData("$id", {
                dismissProgress()
                tvName.text = it.assetCheckOrderName
                list = it.assetVOList
                assetNum = list.size
                progress.max = assetNum
                tvCount.text = "${list.size}"
                tvRealCount.text = "${it.checkNum}"
                tvLoseCount.text = "${it.deficiencyNumber}"
                tvErrorCount.text = "${it.abnormalNumber}"
                mAdapter.setNewInstance(list)
                list.forEachIndexed { index, item ->
                    LogUtils.i("uid 订单 ${item.uid}")
                    mUidMap[item.uid] = AssetVO(item.assetId, item.assetName, item.uid, 1, index)
                }

            }, {
                dismissProgress()
                showToast(it)
            })
        } else {
            showProgress()
            model.requestDataFromLocation("$id", {
                dismissProgress()
                tvName.text = it.name
                list = it.assetVOList
                assetNum = list.size
                progress.max = assetNum
                if(it.shouldHaveNum == 0){
                    tvCount.text = "${list.size}"
                }else{
                    tvCount.text = "${it.shouldHaveNum}"
                }
                tvRealCount.text = "${it.checkNum}"
                tvLoseCount.text = "${it.deficiencyNumber}"
                tvErrorCount.text = "${it.abnormalNumber}"
                tvTime.text = it.lastCheckDate

                if(!it.remark.isNullOrEmpty()){
                    remarkDialog.setContent(it.remark)
                    btnRemark.text = "查看备注"
                }
                mAdapter.setNewInstance(list)
                list.forEachIndexed { index, item ->
                    //LogUtils.i("uid 位置 ${item.uid}")
                    mUidMap[item.uid] = AssetVO(item.assetId, item.assetName, item.uid, 1, index)
                }

            }, {
                dismissProgress()
                showToast(it)
            })
        }
    }

    /**
     * 循环读取超高频数据
     */
    private fun loopReadUHF() {
        while (isStart) {
            val res = mReader?.readTagFromBuffer()
            if(res == null || res.epc == null || filterList.contains(res.epc)){
                continue
            }
            LogUtils.i( "epc = ${res?.epc}")
            SoundUtils.playSound(SoundUtils.SOUND_SUCCESS)
            var newUID = res.epc
            filterList += newUID
            runOnMain {
                if (newUID != null) {
                    scanAllList += newUID
                    tvRealCount.text = "${scanAllList.size}"
                    val value = mUidMap[newUID]
                    if (value != null) {
                        scanRightList += newUID
                        mAdapter.setData(value.index, value)
                        progress.progress = scanRightList.size
                    } else {
                        errorList += newUID
                        tvErrorCount.text = "${errorList.size}"
                    }
                }
            }
        }
    }

    /**
     * 提交数据-按位置提交
     */
    private fun submitByLocation() {
        showProgress()
        val json = LocationSubmitJson("$id",tvTime.text.toString(), remark,scanAllList.toList())
        model.submitLocation(json,{
            dismissProgress()
            btnSubmit.text = "已提交"
            btnSubmit.setBackgroundColor(getColor(R.color.yellow))
            showToast("提交成功")
        },{
            dismissProgress()
            showToast(it)
        })
    }

    /**
     * 提交数据-按订单提交
     */
    private fun submitByOrder() {
        showProgress()
        val json = OrderSubmitJson("$id",tvTime.text.toString(), remark,scanAllList.toList())
        model.submitOrder(json,{
            dismissProgress()
            btnSubmit.text = "已提交"
            btnSubmit.setBackgroundColor(getColor(R.color.yellow))
            showToast("提交成功")
        },{
            dismissProgress()
            showToast(it)
        })
    }

    override fun onDestroy() {
        super.onDestroy()
        SoundUtils.release()
        if(Build.MODEL == "C72"){
            mReader?.stopInventory()
            mReader?.free()
        }
    }

    override fun onItemClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) {
        val item = adapter.getItem(position) as AssetVO
        if(item.type == 2){
            showProgress()
            model.searchName(errorList.toMutableList(),{
               dismissProgress()
                it.forEach{
                    val newItem = AssetVO(item.assetId,it.name,item.uid,3,assetNum)
                    mAdapter.setData(assetNum,newItem)
                    assetNum++
                }
            },{
                dismissProgress()
                showToast(it)
            })
        }
    }

    override fun onKeyDown() {
        if(lifecycle.currentState == Lifecycle.State.RESUMED){
            openOrCloseUHF()
        }
    }
}